package pvt.delez.pa.maven;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.eclipse.core.runtime.Path;

public class ZipFileStructure {
    private ZipFile zipFile;

    private ZipEntry root = new ZipEntry("/");//$NON-NLS-1$

    /**
     * Creates a <code>ZipFileStructureProvider</code>, which will operate
     * on the passed zip file.
     *
     * @param sourceFile the zip file used to create this structure provider
     */
    public ZipFileStructure(ZipFile sourceFile) {
        super();
        zipFile = sourceFile;
    }

	public ZipEntry getEntry(String regex) {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if(entry.getName().matches(regex)){
            	return entry;
            }
        }
        return null;
    }

	public InputStream getContents(Object element) {
        try {
            return zipFile.getInputStream((ZipEntry) element);
        } catch (IOException e) {
            return null;
        }
    }

 	public String getFullPath(Object element) {
        return ((ZipEntry) element).getName();
    }

 	public String getLabel(Object element) {
        if (element.equals(root)) {
			return ((ZipEntry) element).getName();
		}

        return new Path(((ZipEntry) element).getName()).lastSegment();
    }

    /**
     * Returns the entry that this importer uses as the root sentinel.
     *
     * @return java.util.zip.ZipEntry
     */
    public ZipEntry getRoot() {
        return root;
    }

    /**
     * Returns the zip file that this provider provides structure for.
     *
     * @return the zip file this provider provides structure for
     */
    public ZipFile getZipFile() {
        return zipFile;
    }


	public boolean isFolder(Object element) {
        return ((ZipEntry) element).isDirectory();
    }
}
